package com.yotoodesign.dianba.app;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.widget.TabHost;
import android.widget.Toast;

import com.baidu.location.LocationClient;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.yotoodesign.core.common.IGlobalApplication;
import com.yotoodesign.core.util.LoadDataAsynTask;
import com.yotoodesign.core.util.StringUtil;
import com.yotoodesign.dianba.bean.Album;
import com.yotoodesign.dianba.bean.MicroBlogUser;
import com.yotoodesign.dianba.bean.Singer;
import com.yotoodesign.dianba.bean.Song;
import com.yotoodesign.dianba.bean.Tag;
import com.yotoodesign.dianba.ui.MainActivity;
import com.yotoodesign.dianba.ui.MyGeneralListener;
import com.yotoodesign.dianba.ui.MyLocationListener;
import com.yotoodesign.dianba.ui.MySearchListener;
import com.yotoodesign.dianba.util.Constant;
import com.yotoodesign.dianba.util.WeiboConstant;

/**
 * 全局应用基类
 * 临时存储应用数据
 * @author zhuchuanming
 *
 */
public class GlobalApplication extends Application implements IGlobalApplication {
	
	private static GlobalApplication app = null;

	public SharedPreferences preferences;  // 本地存储
	public static Activity activity;//当前活动
	public boolean isConnected = false;//网络是否连接
	
	public TabHost tabHost;
	
	public LocationClient mLocationClient = null;
	public MyLocationListener myListener = new MyLocationListener();
	//当前位置
	public GeoPoint currentPoint;
	public BMapManager mBMapManager = null;
	
	public MKSearch mMKSearch;
	public MySearchListener searchListener;
	
	public MicroBlogUser currentUser ;
	public boolean logined = false;//是否已经登录
	
	public static String saveListUrl = "http://www.yotoodesign.com/maiba/insert_list.php";
	
	public static ProgressDialog progressDialog;
	
	public static GlobalApplication getInstance(){
		return app;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		preferences = getSharedPreferences("com.yotoodesign.dianba",Context.MODE_PRIVATE);
		
		mLocationClient = new LocationClient( this );
		mLocationClient.registerLocationListener( myListener );
		
		//初始化搜索
		initEngineManager(this);
		mMKSearch = new MKSearch();
		MKSearch.setPoiPageCapacity(20);
		searchListener = new MySearchListener();
		mMKSearch.init(mBMapManager, searchListener);//注意，MKSearchListener只支持一个，以最后一次设置为准
		
		app = this;
		
		
	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
	}

	@Override
	public void setActivity(Activity activity) {
		this.activity = activity;
	}
	
	@Override
	//退出之前调用mapadpi的destroy()函数，避免重复初始化带来的时间消耗
	public void onTerminate() {
		// TODO Auto-generated method stub
	    if (mBMapManager != null) {
            mBMapManager.destroy();
            mBMapManager = null;
        }
		super.onTerminate();
	}
	
	/*
	 * 获取主活动
	 */
	public static MainActivity getMainActivity(){
		return (MainActivity)activity;
	}
	
	/*
	 * 加载我的列表
	 */
	public Album loadAsList(String key){
		Album album = null;
		ArrayList<Song> songlist = new ArrayList<Song>();
		String songAlbum = preferences.getString(key, null);
		if(songAlbum != null && !songAlbum.equals("")){
			String[] list = songAlbum.split("&");
			if(list.length==3){
				album = new Album();
				album.setId(key);
				album.setName(list[0]);
				album.setDesc(list[1]);
				//取歌曲列表
				String[] songs = list[2].split("#");
				for(int i = 0;i<songs.length;i++){
					String[] s = songs[i].split(",");
					Song song = new Song();
					song.setName(s[0]);
					
					Singer singer = new Singer();
					singer.setName(s[1]);
					singer.setImageUrl(s[2]);
					song.setSinger(singer);
					
					songlist.add(song);
				}
				
				album.setSongList(songlist);
			}
		}
		
		return album;
	}
	
	/*
	 * 保存我的列表
	 * Constant.TOP10_SONG
	 */
	public void saveAsList(String key,ArrayList<Song> values,String listName,String listDesc){
		String mySongKeys = preferences.getString(Constant.MY_SONG_KEYS, "");
		Editor editor = preferences.edit();
		String song10 = listName+"&"+listDesc+"&";
		for(Iterator<Song> it = values.iterator();it.hasNext();){
			Song song = (Song)it.next();
			song10 += song.getName() + "," + song.getSinger().getName() + ","
					+ song.getSinger().getImageUrl() + "#";
			
		}
		if(song10.endsWith("#")){
			song10 = song10.substring(0, song10.length()-1);
		}
		
		if(key==null || key.equals("")){
			key = StringUtil.randomString(10);
		}
		
		editor.putString(key, song10);
		
		//保存点歌单键值，已经保存过的key就不保存了
		if(mySongKeys!=null && mySongKeys.indexOf(key)==-1){
			mySongKeys += ","+key;
		}
		
		editor.putString(Constant.MY_SONG_KEYS, mySongKeys);
		
		editor.commit();
		
		//如果用户登录了新浪微博，则保存数据到服务器端
//		if(GlobalApplication.getInstance().logined){
//			String params = getParams(values,listName,listDesc);
//			Log.i(Constant.DIANBA,"params>"+params);
//			LoadDataAsynTask.loadDataFromUrl(saveListUrl, params,WeiboConstant.EXTERNAL_DIR_CACHE);
//		}
	}
	
	/*
	 * 加载我的列表
	 */
	public ArrayList<Album> loadMyAlbums(){
		ArrayList<Album> result = new ArrayList<Album>();
		String mySongKeys = preferences.getString(Constant.MY_SONG_KEYS, "");

		String[] keys = mySongKeys.split(",");
		for(int i =0 ;i<keys.length;i++){
			if(!keys[i].equals("")){
				Album album =loadAsList(keys[i]);
				if(album!=null){
					result.add(album);
				}
			}
		}
		
		return result;
	}
	
	/*
	 * 从列表中删除指定的点歌单，并从本地存储中删除
	 */
	public void removeMyAlbum(ArrayList<Album> albums,String albumName){
		for(Iterator<Album> it = albums.iterator();it.hasNext();){
			Album album = it.next();
			if(album.getName().equals(albumName)){
				albums.remove(album);
				
				Editor editor = preferences.edit();
				editor.remove(album.getId());
				
				String mySongKeys = preferences.getString(Constant.MY_SONG_KEYS, "");
				Log.i(Constant.DIANBA,"before>"+Constant.MY_SONG_KEYS);
				mySongKeys = mySongKeys.replace(","+album.getId(), "");
				Log.i(Constant.DIANBA,"after>"+Constant.MY_SONG_KEYS);
				editor.putString(Constant.MY_SONG_KEYS, mySongKeys);
				editor.commit();
				break;
			}
		}
	}
	
	/*
	 * 删除我的所有点歌单
	 */
	public void removeAllAlbum(ArrayList<Album> albums){
		Editor editor = preferences.edit();
		editor.putString(Constant.MY_SONG_KEYS, "");
		
		for(Iterator<Album> it = albums.iterator();it.hasNext();){
			Album album = it.next();
			editor.remove(album.getId());
		}
		editor.commit();
		
		albums.clear();
	}
	
	//加载指定点歌单中的歌曲列表
	public ArrayList<Song> loadMySongList(ArrayList<Album> albums,String listName){
		ArrayList<Song> result = new ArrayList<Song>();
		for(Iterator<Album> it = albums.iterator();it.hasNext();){
			Album album = it.next();
			if(album.getName().equals(listName)){
				result = album.getSongList();
				break;
			}
		}
		
		return result;
	}
	
	/*
	 * 清空保存的数据
	 */
	public void clearList(){
		Editor editor = preferences.edit();
		editor.clear();
		editor.commit();
	}
	
	public void initEngineManager(Context context) {
        if (mBMapManager == null) {
            mBMapManager = new BMapManager(context);
        }

        if (!mBMapManager.init(Constant.BAIDU_MAP_KEY,new MyGeneralListener())) {
            Toast.makeText(this, "BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
        }
	}
	
	public static void alert(String content){
		AlertDialog.Builder builder = new Builder(GlobalApplication.activity);
		builder.setTitle("提示信息")
		.setMessage(content)
		.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
			}
		})
		.show();
	}
	
	public ArrayList<Tag> loadMyTags(){
		ArrayList<Tag> tags = new ArrayList<Tag>();
		String myTags = preferences.getString(Constant.MY_TAGS, "");
		String[] tagsAry = myTags.split(",");
		for(int i = 0;i<tagsAry.length;i++){
			if(tagsAry[i].equals("")==false){
				Tag tag = new Tag(tagsAry[i]);
				tags.add(tag);
			}
		}
		
		return tags;
	}
	
	public void saveTag(Tag tag){
		String myTags = preferences.getString(Constant.MY_TAGS, "");
		Editor editor = preferences.edit();
		
		myTags += ","+tag.getName();
		
		editor.putString(Constant.MY_TAGS,myTags);
		editor.commit();
	}
	
	public void deleteTag(Tag tag){
		String myTags = preferences.getString(Constant.MY_TAGS, "");
		Editor editor = preferences.edit();
		
		myTags = myTags.replace(","+tag.getName(), "");
		
		editor.putString(Constant.MY_TAGS,myTags);
		editor.commit();
	}
	
	//获取参数
	public String getParams(ArrayList<Song> values,String listName,String listDesc){
		String params = "";
		
		SimpleDateFormat seq = new SimpleDateFormat("yyyyMMDDHHmmss");
		
		MicroBlogUser user = GlobalApplication.getInstance().currentUser;
		if(user!=null){
			params += "id="+ user.getId()+"_"+seq.format(new Date())+"&";//ID后面跟时间戳
		}
		
		params += "name=" + listName+"&";
		params += "desc=" + listDesc+"&";
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
		String createDate = sdf.format(new Date());
		params += "createDate=" + createDate+"&";
		
		String songs_singers = "";
		for(int i = 0;i<values.size();i++){
			Song song = values.get(i);
			songs_singers += song.getId()+",";
			songs_singers += song.getName()+",";
			songs_singers += song.getSinger().getId()+",";
			songs_singers += song.getSinger().getName()+"::";
		}
		
		//去掉最后的::
		if(songs_singers.substring(songs_singers.length()-2).equals("::")){
			songs_singers = songs_singers.substring(0, songs_singers.length()-2);
		}
		
		params += "songs_singers=" + songs_singers;
		
		return params;
	}
	
	public static void showProgress(String title,String message){
		progressDialog = new ProgressDialog(activity);
        progressDialog.setTitle(title);
        progressDialog.setMessage(message);
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
        progressDialog.show();
	}
	
	public static void hideProgress(){
		if(progressDialog!=null){
			progressDialog.dismiss();
		}
	}
	
	
}
